package com.oddfar.campus.service.controller.admin;


import com.oddfar.campus.common.result.Result;
import com.oddfar.campus.common.utils.HttpServletUtil;
import com.oddfar.campus.model.campus.SysUser;
import com.oddfar.campus.model.user.LoginUser;
import com.oddfar.campus.service.mapper.SysUserMapper;
import com.oddfar.campus.service.service.SysUserService;
import com.oddfar.campus.service.service.impl.SysUserServiceImpl;
import com.oddfar.campus.service.utils.SecurityUtils;
import com.oddfar.campus.service.utils.TokenService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员管理")
public class AdminInfoController {

    @Autowired
    TokenService tokenService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserService sysUserService;

    @GetMapping( "info")
    public Result info() {

        LoginUser loginUser = tokenService.getLoginUser(HttpServletUtil.getRequest());

        SysUser user = loginUser.getUser();

        HashMap<String, Object> responseData = new HashMap<>();

        responseData.put("roles", loginUser.getPermissions());
        responseData.put("name", user.getUserName());
        responseData.put("avatar", user.getImageUrl());

        return Result.ok(responseData);
    }

    @PutMapping("updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        SysUser user = sysUserMapper.selectById(SecurityUtils.getUserId());
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return Result.fail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Result.fail("新密码不能与旧密码相同");
        }
        user.setPassword(new SysUserServiceImpl().BCrypt(newPassword));
        sysUserService.updateById(user);
        return Result.ok();
    }
}
